import React, { useState, useEffect } from 'react';
import { View, Text, Pressable, Image, FlatList, StyleSheet } from 'react-native';
import { useNavigation } from '@react-navigation/native';
import Icon from 'react-native-vector-icons/Ionicons';
import SearchButton from './SearchButton';
import PostDetail from './PostDetail';
import Search from './search.js';
import axios from 'axios';
const HotText = () => {
    const navigation = useNavigation();
    const [selectedTab, setSelectedTab] = useState('校内十大');
    const [hotPosts, setHotPosts] = useState([]);
    const [historyPosts, setHistoryPosts] = useState([]);
    const [view, setView] = useState([]);
    const [historyView, setHistoryView] = useState([]);
    const [refreshing, isRefresh] = useState(true);
    const plate = [
        { name: '身边趣事', iconName: 'chatbubbles', boardexplain: '用于分享你身边真实、有趣、温暖的见闻。不可滥用此分类，无意义的水贴会被删除乃至封禁！' },
        { name: '创作分享', iconName: 'arrow-undo-sharp', boardexplain: '用于分享你或授权的有益大众的经验或内容' },
        { name: '吐槽爆料', iconName: 'flash', boardexplain: '谨慎用此分类，侵犯他人权益的会被删帖与封禁' },
        { name: '时事新闻', iconName: 'newspaper', boardexplain: '发前请善用搜索，须以图、文或链接等形式声明来源。禁止转载外网新闻，禁止政治敏感信息，一经发现，直接封禁' },
        { name: '情感', iconName: 'heart', boardexplain: '用于分享亲情、友情、爱情中的酸甜苦辣' },
        { name: '朵朵有嘻哈', iconName: 'headset', boardexplain: '请尽量保证所发的段子或搞笑图近期在此板块未发布过' },
        { name: '电子游戏', iconName: 'game-controller', boardexplain: '禁止求群和拉群！' },
        { name: '学业疑难', iconName: 'library', boardexplain: '禁止代课、代签到、代写作业、代考等内容。本版严禁出售及求购书籍资料！' },
        { name: '日常生活', iconName: 'partly-sunny', boardexplain: '请务必确保已尽量使用不同的关键词组合搜索过类似问题，本版不可发布求购帖，必须发布在物品所属板块' },
        { name: '寻物招领', iconName: 'storefront', boardexplain: '格式：实物描述+时间地点  涉及的隐私信息，如照片、身份证号码等需要打码哟~证件类请务必将失主全名打在正文里' },
        { name: '学习顾问', iconName: 'person-add', boardexplain: '学生介绍+具体要求+具体薪资（不可面议） 薪资过低引起争议的，可能会被删除乃至封禁。请发布前搜索了解历史内容，获取市场行情价格' },
        { name: '全职', iconName: 'person', boardexplain: '具体要求+具体薪资' },
        { name: '实习', iconName: 'timer', boardexplain: '具体要求+具体薪资' },
        { name: '短期兼职', iconName: 'school', boardexplain: '具体要求+具体薪资' },
        { name: '免费赠送', iconName: 'gift', boardexplain: '赠送你不需要的物品给他人' },
        { name: '鞋服包饰', iconName: 'bag', boardexplain: '格式：名称+原价+售价+使用情况+其他描述' },
        { name: '美妆护肤', iconName: 'shirt', boardexplain: '格式：名称+原价+售价+使用情况+其他描述' },
        { name: '书籍资料', iconName: 'book', boardexplain: '格式：列出详细的闲置书籍目录，会获取更大的曝光流量，并标注价格  本类帖子由于数量过多，不会出现在首页时间线中' },
        { name: '电子数码', iconName: 'phone-portrait', boardexplain: '格式：名称+原价+售价+使用情况+其他描述' },
        { name: '生活百货', iconName: 'bag-remove', boardexplain: '格式：名称+原价+售价+使用情况+其他描述 不得在此板块发布书籍类闲置' },
        { name: '电器家具', iconName: 'tv', boardexplain: '格式：名称+原价+售价+使用情况+其他描述' },
        { name: '食品饮料', iconName: 'fast-food', boardexplain: '格式：名称+原价+售价+使用情况+其他描述' },
        { name: '运动健身', iconName: 'barbell', boardexplain: '格式：名称+原价+售价+使用情况+其他描述' },
        { name: '票卡服务', iconName: 'card', boardexplain: '格式：名称+原价+售价+使用情况+其他描述 禁止买卖发票！' },
        { name: '租房合租', iconName: 'business', boardexplain: '格式：地址+配套设施+价格+其他描述' },
    ]
    // const handleRefresh = () => {
    //     isRefresh(true);
    //     getHotPost();
    // }
    const getHotPost = () => {
        axios.get('http://47.111.227.58:3000/dynamic/getDynamicView')
            .then(res => {
                // console.log(res.data);
                setHotPosts(res.data.results);
                const initialView = res.data.results.map(item => item.view);
                setView(initialView)
            })
            .catch(error => {
                console.error(error);
            });
    }
    const getHistoryPost = () => {
        axios.get('http://47.111.227.58:3000/dynamic/getHistoryDynamicView')
            .then(res => {
                // console.log(res.data);
                setHistoryPosts(res.data.results);
                const initialView = res.data.results.map(item => item.view);
                setHistoryView(initialView)
            })
            .catch(error => {
                console.error(error);
            });
    }
    const handlePostClick = (postId, index) => {
        navigation.navigate('PostDetail', { postId: postId });
        let newView = [...view];
        newView[index] = Number(newView[index]) + 1;
        setView(newView);
        axios.post('http://47.111.227.58:3000/dynamic/updataIdDynamicView', {
            data: {
                id: postId,
                view: newView[index]
            }
        }).then(res => {
            console.log(res.data);
        });
    };
    const handleHistoryPostClick = (postId, index) => {
        navigation.navigate('PostDetail', { postId: postId });
        let newView = [...historyView];
        newView[index] = Number(newView[index]) + 1;
        setView(newView);
        axios.post('http://47.111.227.58:3000/dynamic/updataIdDynamicView', {
            data: {
                id: postId,
                view: newView[index]
            }
        }).then(res => {
            console.log(res.data);
        });
    };
    useEffect(() => {
        (async () => {
            getHotPost()
            getHistoryPost()
        })();
    }, []);

    const renderPlate = ({ item, index }) => {
        const formattedIndex = (index + 1).toString().padStart(2, '0');
        return (
            <Pressable
            style={styles.plateItem}
            onPress={() => navigation.navigate('SearchPlateContent', {
                boardName: item.name,
                // boardexplain: item.boardexplain,
            })}
            >
                <View style={styles.plateContent}>

                    <View style={styles.plateContentLeft}>
                        <View style={styles.postPlateIndexContainer}>
                            <Text style={styles.postPlateIndex}>{formattedIndex}</Text>
                        </View>
                        <Icon name={item.iconName} size={28} color="#EB7A76" />
                    </View>
                    <View style={styles.plateContentRight}>
                        <Text style={styles.plateContentText1}>{item.name}</Text>
                        <Text style={styles.plateContentText2}>{item.boardexplain}</Text>
                    </View>
                </View>
            </Pressable>
        )
    }
    const renderPost = ({ item, index }) => {
        const formattedIndex = (index + 1).toString().padStart(2, '0');
        return (
            <Pressable
                style={styles.postItem}
                onPress={() => handlePostClick(item.id, index)}
            >
                <View style={styles.postContent}>
                    <View style={styles.postDetail}>
                        <View style={styles.postIndexContainer}>
                            <Text style={styles.postIndex}>{formattedIndex}</Text>
                        </View>
                        <Text style={styles.postStats}>
                            {item.comments} 评论 {item.likes} 点赞 {item.view} 阅读
                        </Text>
                    </View>
                    <Text style={styles.postTitle}>{item.desc}</Text>
                    <View style={styles.userDetail}>
                        <Image style={styles.userAvatar} source={{ uri: item.userImg }} />
                        <Text style={styles.username}>{item.username}</Text>
                        <Text style={styles.boardText}>#{item.board}</Text>
                    </View>
                </View>
                {item.imgUrl && (
                    <Image style={styles.postImage} source={{ uri: item.imgUrl }} />
                )}
            </Pressable>
        );
    };
    const renderHistoryPost = ({ item, index }) => {
        const formattedIndex = (index + 1).toString().padStart(2, '0');
        return (
            <Pressable
                style={styles.postItem}
                onPress={() => handleHistoryPostClick(item.id, index)}
            >
                <View style={styles.postContent}>
                    <View style={styles.postDetail}>
                        <View style={styles.postIndexContainer}>
                            <Text style={styles.postIndex}>{formattedIndex}</Text>
                        </View>
                        <Text style={styles.postStats}>
                            {item.comments} 评论 {item.likes} 点赞 {item.view} 阅读
                        </Text>
                    </View>
                    <Text style={styles.postTitle}>{item.desc}</Text>
                    <View style={styles.userDetail}>
                        <Image style={styles.userAvatar} source={{ uri: item.userImg }} />
                        <Text style={styles.username}>{item.username}</Text>
                        <Text style={styles.boardText}>#{item.board}</Text>
                    </View>
                </View>
                {item.imgUrl && (
                    <Image style={styles.postImage} source={{ uri: item.imgUrl }} />
                )}
            </Pressable>
        );
    };

    return (
        <View style={styles.container}>
            {/* Tab栏 */}
            <View style={styles.tabBar}>
                {['校内十大', '热门板块', '历史热帖'].map(tab => (
                    <Pressable
                        key={tab}
                        style={[styles.tabItem, selectedTab === tab && styles.tabItemSelected]}
                        onPress={() => setSelectedTab(tab)}
                    >
                        <Text style={styles.tabText}>{tab}</Text>
                    </Pressable>
                ))}
            </View>

            {/* 帖子列表 */}
            <FlatList
                data={selectedTab === '校内十大' ? hotPosts : selectedTab === '热门板块' ? plate : historyPosts}
                renderItem={selectedTab === '校内十大' ? renderPost : selectedTab === '热门板块' ? renderPlate : renderHistoryPost}
                keyExtractor={item => item.id}
            />
            <SearchButton navigateToSearch={() => navigation.navigate('Search')} />
        </View>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#f5f5f5',
    },
    tabBar: {
        flexDirection: 'row',
        justifyContent: 'space-around',
        backgroundColor: '#fff',
        boxShadow: '0px 2px 2px rgba(0, 0, 0, 0.1)',
        elevation: 3,
    },
    tabItem: {
        alignItems: 'center',
        justifyContent: 'center',
        padding: 10,
    },
    tabItemSelected: {
        borderBottomWidth: 2,
        borderBottomColor: '#EB7A76',
    },
    tabText: {
        fontSize: 16,
        color: '#333',
    },
    postItem: {
        flexDirection: 'row',
        alignItems: 'flex-start',
        backgroundColor: '#fff',
        padding: 10,
        marginVertical: 5,
    },
    postContent: {
        flex: 1,
    },
    postDetail: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    postIndexContainer: {
        backgroundColor: '#f7ca64',
        paddingHorizontal: 6,
        paddingVertical: 2,
        borderRadius: 4,
        marginRight: 10,
    },
    postIndex: {
        fontWeight: 'bold',
        color: '#fff',
    },
    postPlateIndexContainer: {
        backgroundColor: '#f7ca64',
        paddingHorizontal: 2,
        paddingVertical: 0,
        borderRadius: 4,
        position: 'absolute',
        top: 2,
        left: -1,
        // marginRight: 10,
    },
    postPlateIndex: {
        fontWeight: 'bold',
        color: '#fff',
    },
    postStats: {
        fontSize: 14,
        color: '#666',
    },
    postTitle: {
        fontSize: 17,
        color: 'black',
        marginTop: 8,
    },
    postImage: {
        width: 80,
        height: 80,
        borderRadius: 4,
        marginLeft: 10,
    },
    userDetail: {
        flexDirection: 'row',
        alignItems: 'center',
        marginTop: 8,
    },
    userAvatar: {
        width: 20,
        height: 20,
        borderRadius: 10,
        marginRight: 8,
    },
    username: {
        fontSize: 14,
        color: '#333',
    },
    boardText: {
        height: 25,
        width: 55,
        backgroundColor: '#DDE1EA',
        color: '#576B94',
        marginBottom: 5,
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        fontSize: 10,
        marginLeft: 'auto',
        marginRight: 5,
        // fontWeight: 'bold',
    },
    plateContent: {
        flexDirection: 'row',
        backgroundColor: '#fff',
        marginBottom: 5,
        height: 65,
    },
    plateContentLeft: {
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        paddingLeft: 10,
        paddingRight: 10,
    },
    plateContentRight: {
        flexDirection: 'column',
        display: 'flex',
        justifyContent: 'center',
        // alignItems: 'center',
    },
    plateContentText1: {
        fontSize: 16,
        fontWeight: 'bold',
        color: '#222222',
        marginBottom: 5,
    },
    plateContentText2: {
        fontSize: 12,
        color: '#999999'
    }
});

export default HotText;
